<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .search {
            text-align: center;
        }

        table {
            width: 400px;
            text-align: center;
            margin: 100px auto;
        }
    </style>
</head>

<body>
    <div class="search">
        按照价格查询：<input type="text" class="start"> - <input type="text" class="end">
        <button class="search-price">搜索</button>
        按商品名称查询: <input type="text" class="product"><button class="search-pro">查询</button>
    </div>

    <table border="1" cellspacing="0">
        <thead>
            <tr>
                <th>id</th>
                <th>产品名称</th>
                <th>价格</th>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>
    <script>
        var data = [{
            id: 1,
            pname: '小米',
            price: 3999
        }, {
            id: 2,
            pname: 'oppo',
            price: 999
        }, {
            id: 3,
            pname: '荣耀',
            price: 1299
        }, {
            id: 4,
            pname: '华为',
            price: 1999
        },];
        var tbody = document.querySelector('tbody');
        var search_price = document.querySelector('.search-price');
        var start = document.querySelector('.start');
        var end = document.querySelector('.end')
        var search_pro = document.querySelector('.search-pro');
        var product = document.querySelector('.product');
        //动态创建表格
        setData(data);
        //封装一个函数
        function setData(myData) {
            //先清空一遍tbody以免数据重复
            tbody.innerHTML = '';
            myData.forEach(function (value) {
                var tr = document.createElement('tr');
                tr.innerHTML = '<td>' + value.id + '</td> <td>' + value.pname + '</td> <td>' + value.price + '</td>';
                tbody.appendChild(tr);
            })
        }
        //绑定查询价格事件
        search_price.addEventListener('click', function () {
            var newData = data.filter(function (value) {
                return value.price >= start.value && value.price <= end.value;
            })
            // console.log(newData);
            setData(newData);
        })
        //绑定查询名称事件
        search_pro.addEventListener('click', function () {
            var arr = [];
            data.some(function (value) {  //在数组中查询唯一的元素用some效率高
                if (product.value === value.pname) {
                    arr.push(value);
                    //只返回 true false  效率高
                    return true;
                }
            })
            setData(arr);
        })
    </script>
</body>

</html>